<template>
  <div class="app-container">
    <div>
      <el-button type="primary" @click="refresh" size="small" icon="el-icon-refresh">刷新</el-button>
    </div>
    <el-table :data="rolesList" v-loading="loading" :header-cell-style="{background:'#eef1f6',color:'#606266'}"
      style="width: 100%;margin-top:30px;" border row-key="id" default-expand-all
      :tree-props="{children: 'children', hasChildren: 'hasChildren'}">
      <el-table-column label="角色名称" prop="RoleName">
        <template slot-scope="scope">{{ scope.row.RoleName }}</template>
      </el-table-column>
      <el-table-column label="标识码" width="220" prop="Code">
        <template slot-scope="scope">{{ scope.row.Code }}</template>
      </el-table-column>
      <el-table-column label="创建时间" width="220" prop="CreateTime">
        <template slot-scope="scope">{{ scope.row.CreateTime | formatDateSec}}</template>
      </el-table-column>
      <el-table-column align="center" width="200" label="操作">
        <template slot-scope="scope">
          <el-button type="text" size="mini" @click="handleEdit(scope)" icon="el-icon-check">配置权限</el-button>
          <el-dropdown>
            <span class="el-dropdown-link">
              <!-- <i class="el-icon-s-operation  el-icon--right">更多</i> -->
              <el-button type="text" size="mini" icon="el-icon-more">更多</el-button>
            </span>
            <el-dropdown-menu slot="dropdown">
              <el-dropdown-item>
                <el-button type="text" size="mini" @click="handleViewPer(scope)" icon="el-icon-check">权限查看</el-button>
              </el-dropdown-item>
              <el-dropdown-item>
                <el-button type="text" size="mini" @click="handleUser(scope)" icon="el-icon-user">配置用户</el-button>
              </el-dropdown-item>
              <!-- <el-dropdown-item>
                <el-button type="text" size="mini" @click="viewUser(scope)" icon="el-icon-user">用户查看</el-button>
              </el-dropdown-item> -->
            </el-dropdown-menu>
          </el-dropdown>
        </template>
      </el-table-column>
    </el-table>

    <el-dialog :visible.sync="dialogVisible" :title="'配置权限'" :close-on-click-modal="false" top="3vh">
      <el-form :model="role" :rules="rules" ref="role" label-width="100px" label-position="right">
        <el-form-item label="父级角色" prop="ParentID">
          <el-input v-model="role.ParentName" placeholder="父级角色" :disabled="true" />
        </el-form-item>
        <el-form-item label="角色名称" prop="RoleName">
          <el-input v-model="role.RoleName" placeholder="角色名称" :disabled="true" />
        </el-form-item>
        <el-form-item label="菜单">
          <el-tree ref="tree" :data="routesData" :props="defaultProps" show-checkbox default-expand-all node-key="id"
            class="permission-tree" />
        </el-form-item>
        <div style="text-align:right">
          <el-button type="danger" @click="dialogVisible=false">取消</el-button>
          <el-button type="primary" @click="confirmRole('role')">确认</el-button>
        </div>
      </el-form>
    </el-dialog>

    <el-dialog :visible.sync="dialogPerVisible" :title="'查看权限'" :close-on-click-modal="false" top="3vh">
      <el-form :model="role" :rules="rules" ref="role" label-width="100px" label-position="right">
        <el-form-item label="父级角色" prop="ParentID">
          <el-input v-model="role.ParentName" placeholder="父级角色" :disabled="true" />
        </el-form-item>
        <el-form-item label="角色名称" prop="RoleName">
          <el-input v-model="role.RoleName" placeholder="角色名称" :disabled="true" />
        </el-form-item>
        <!-- <el-form-item label="备注">
              <el-input v-model="role.Text" :autosize="{ minRows: 2, maxRows: 4}" type="textarea" placeholder="备注" />
            </el-form-item> -->
        <el-form-item label="菜单">
          <el-tree ref="tree" :data="roleRoutes" :props="defaultProps" default-expand-all node-key="id"
            class="permission-tree" />
        </el-form-item>
        <div style="text-align:right">
          <el-button type="danger" @click="dialogPerVisible=false">取消</el-button>
        </div>
      </el-form>
    </el-dialog>

    <el-dialog :visible.sync="dialogUserVisible" :title="role.RoleName" :close-on-click-modal="false" width="80%"
      top="3vh">
      <el-tabs v-model="activeName" type="card" @tab-click="handleClick">
        <el-tab-pane label="已授权" name="0">
          <div>
            <el-select size="small" v-model="userViewModel.AreaCode" placeholder="区域" clearable filterable
              style="width: 150px;margin-right: 15px;" class="filter-item" @change="AreaSearch">
              <el-option v-for="item in areaDatas" :key="item.AreaCode" :label="item.AreaName" :value="item.AreaCode">
              </el-option>
            </el-select>
            <el-select size="small" v-model="userViewModel.ProvinceCode" placeholder="省份" clearable filterable
              style="width: 150px;margin-right: 15px;" class="filter-item" @change="ProvinceSearch">
              <el-option v-for="item in provinceDatas" :key="item.ProvinceCode" :label="item.ProvinceName"
                :value="item.ProvinceCode"></el-option>
            </el-select>
            <el-select size="small" v-model="userViewModel.CityCode" placeholder="城市" clearable filterable
              style="width: 250px;margin-right: 15px;" class="filter-item" @change="CitySearch">
              <el-option v-for="item in cityDatas" :key="item.CityCode" :label="item.CityName" :value="item.CityCode">
              </el-option>
            </el-select>
            <el-input v-model="userViewModel.SGMWRecordJob" size="small" placeholder="SGMW备案岗位" style="width: 200px;"
            class="filter-item" @keyup.enter.native="queryUser" />
          </div>
          <div style="margin-top: 15px;">
            <el-input v-model="userViewModel.UserName" size="small" placeholder="姓名" style="width: 200px;"
              class="filter-item" @keyup.enter.native="queryUser" />
            <el-input v-model="userViewModel.LoginName" size="small" placeholder="登录名" style="width: 200px;"
              class="filter-item" @keyup.enter.native="queryUser" />
            <el-input v-model="userViewModel.Unumber" size="small" placeholder="职员代码" style="width: 200px;"
              class="filter-item" @keyup.enter.native="queryUser" />
            <el-input v-model="userViewModel.AgentNumber" size="small" placeholder="经销商号码" style="width: 200px;"
              class="filter-item" @keyup.enter.native="queryUser" />
            <el-select v-model="userViewModel.UserType" size="small" filterable placeholder="请选择" style="width: 200px;">
              <el-option v-for="item in userTypeList" :key="item.value" :label="item.label" :value="item.value">
              </el-option>
            </el-select>
            <el-button type="primary" @click="queryUser" size="small" icon="el-icon-search">查询</el-button>
            <el-button type="primary" @click="refreshUser" size="small" icon="el-icon-refresh">刷新</el-button>
            <!-- <el-button type="primary" @click="handleBatchRoleUser(0)" size="small" icon="el-icon-user">授权搜索用户
            </el-button> -->
            <el-button type="primary" @click="handleBatchRoleUser(0)" size="small" icon="el-icon-user">取消授权搜索用户
            </el-button>
          </div>
          <el-table v-loading="loading" :header-cell-style="{background:'#eef1f6',color:'#606266'}" :data="userList"
            style="width: 100%;margin-top:30px;" border @sort-change="sortChange" ref="multipleTable"
            @selection-change="handleSelectionChange">
            <el-table-column type="selection" width="55">
            </el-table-column>
            <el-table-column label="姓名" prop="UserName">
              <template slot-scope="scope">{{ scope.row.UserName }}</template>
            </el-table-column>
            <el-table-column label="职员代码" prop="Unumber">
              <template slot-scope="scope">{{ scope.row.Unumber }}</template>
            </el-table-column>
            <el-table-column label="经销商号码" prop="AgentNumber">
              <template slot-scope="scope">{{ scope.row.AgentNumber }}</template>
            </el-table-column>
            <el-table-column label="区域">
              <template slot-scope="scope">{{ scope.row.AreaName }}</template>
            </el-table-column>
            <el-table-column label="省份">
              <template slot-scope="scope">{{ scope.row.ProvinceName }}</template>
            </el-table-column>
            <el-table-column label="城市">
              <template slot-scope="scope">{{ scope.row.CityName }}</template>
            </el-table-column>
            <el-table-column label="登录名" prop="LoginName">
              <template slot-scope="scope">{{ scope.row.LoginName }}</template>
            </el-table-column>
            <el-table-column label="SGMW备案岗位" prop="SGMWRecordJob">
              <template slot-scope="scope">{{ scope.row.SGMWRecordJob}}</template>
            </el-table-column>
          </el-table>
          <!-- 分页组件：https://element.eleme.cn/#/zh-CN/component/pagination -->
          <div class="block" style="float:right;margin-top:15px;" v-if="userViewModel.total>0">
            <el-pagination @size-change="handleSizeChange" @current-change="handleCurrentChange"
              :current-page="userViewModel.page" :page-sizes="[10, 20, 30, 40,100]" :page-size="userViewModel.pageSize"
              @prev-click="lastPage" @next-click="nextPage" background layout="total, sizes, prev, pager, next, jumper"
              :total="userViewModel.total"></el-pagination>
          </div>
          <div style="text-align:right;margin-top: 60px;">
            <el-button type="danger" @click="dialogUserVisible=false">关闭</el-button>
            <el-button type="primary" @click="confirmRoleUser(0)">确认取消授权</el-button>
          </div>
        </el-tab-pane>
        <el-tab-pane label="未授权" name="1">
          <div>
            <el-select size="small" v-model="userViewModel.AreaCode" placeholder="区域" clearable filterable
              style="width: 150px;margin-right: 15px;" class="filter-item" @change="AreaSearch">
              <el-option v-for="item in areaDatas" :key="item.AreaCode" :label="item.AreaName" :value="item.AreaCode">
              </el-option>
            </el-select>
            <el-select size="small" v-model="userViewModel.ProvinceCode" placeholder="省份" clearable filterable
              style="width: 150px;margin-right: 15px;" class="filter-item" @change="ProvinceSearch">
              <el-option v-for="item in provinceDatas" :key="item.ProvinceCode" :label="item.ProvinceName"
                :value="item.ProvinceCode"></el-option>
            </el-select>
            <el-select size="small" v-model="userViewModel.CityCode" placeholder="城市" clearable filterable
              style="width: 250px;margin-right: 15px;" class="filter-item" @change="CitySearch">
              <el-option v-for="item in cityDatas" :key="item.CityCode" :label="item.CityName" :value="item.CityCode">
              </el-option>
            </el-select>
            <el-input v-model="userViewModel.SGMWRecordJob" size="small" placeholder="SGMW备案岗位" style="width: 200px;"
            class="filter-item" @keyup.enter.native="queryUser" />
          </div>
          <div style="margin-top: 15px;">
            <el-input v-model="userViewModel.UserName" size="small" placeholder="姓名" style="width: 200px;"
              class="filter-item" @keyup.enter.native="queryUser" />
            <el-input v-model="userViewModel.LoginName" size="small" placeholder="登录名" style="width: 200px;"
              class="filter-item" @keyup.enter.native="queryUser" />
            <el-input v-model="userViewModel.Unumber" size="small" placeholder="职员代码" style="width: 200px;"
              class="filter-item" @keyup.enter.native="queryUser" />
            <el-input v-model="userViewModel.AgentNumber" size="small" placeholder="经销商号码" style="width: 200px;"
              class="filter-item" @keyup.enter.native="queryUser" />
            <el-select v-model="userViewModel.UserType" size="small" filterable placeholder="请选择" style="width: 200px;">
              <el-option v-for="item in userTypeList" :key="item.value" :label="item.label" :value="item.value">
              </el-option>
            </el-select>
            <el-button type="primary" @click="queryUser" size="small" icon="el-icon-search">查询</el-button>
            <el-button type="primary" @click="refreshUser" size="small" icon="el-icon-refresh">刷新</el-button>
            <el-button type="primary" @click="handleBatchRoleUser(1)" size="small" icon="el-icon-user">授权搜索用户
            </el-button>
            <!-- <el-button type="primary" @click="handleBatchRoleUser(1)" size="small" icon="el-icon-user">取消授权搜索用户</el-button> -->
          </div>
          <el-table v-loading="loading" :header-cell-style="{background:'#eef1f6',color:'#606266'}" :data="userList"
            style="width: 100%;margin-top:30px;" border @sort-change="sortChange" ref="multipleTable"
            @selection-change="handleSelectionChange">
            <el-table-column type="selection" width="55">
            </el-table-column>
            <el-table-column label="姓名" prop="UserName">
              <template slot-scope="scope">{{ scope.row.UserName }}</template>
            </el-table-column>
            <el-table-column label="职员代码" prop="Unumber">
              <template slot-scope="scope">{{ scope.row.Unumber }}</template>
            </el-table-column>
            <el-table-column label="经销商号码" prop="AgentNumber">
              <template slot-scope="scope">{{ scope.row.AgentNumber }}</template>
            </el-table-column>
            <el-table-column label="登录名" prop="LoginName">
              <template slot-scope="scope">{{ scope.row.LoginName }}</template>
            </el-table-column>
            <el-table-column label="区域">
              <template slot-scope="scope">{{ scope.row.AreaName }}</template>
            </el-table-column>
            <el-table-column label="省份">
              <template slot-scope="scope">{{ scope.row.ProvinceName }}</template>
            </el-table-column>
            <el-table-column label="城市">
              <template slot-scope="scope">{{ scope.row.CityName }}</template>
            </el-table-column>
            <el-table-column label="SGMW备案岗位" prop="SGMWRecordJob">
              <template slot-scope="scope">{{ scope.row.SGMWRecordJob}}</template>
            </el-table-column>
          </el-table>
          <!-- 分页组件：https://element.eleme.cn/#/zh-CN/component/pagination -->
          <div class="block" style="float:right;margin-top:15px;" v-if="userViewModel.total>0">
            <el-pagination @size-change="handleSizeChange" @current-change="handleCurrentChange"
              :current-page="userViewModel.page" :page-sizes="[10, 20, 30, 40,100]" :page-size="userViewModel.pageSize"
              @prev-click="lastPage" @next-click="nextPage" background layout="total, sizes, prev, pager, next, jumper"
              :total="userViewModel.total"></el-pagination>
          </div>
          <div style="text-align:right;margin-top: 60px;">
            <el-button type="danger" @click="dialogUserVisible=false">关闭</el-button>
            <el-button type="primary" @click="confirmRoleUser(1)">确认授权</el-button>
          </div>
        </el-tab-pane>
      </el-tabs>
    </el-dialog>

    <el-dialog :visible.sync="dialogRoleUserVisible" :title="role.RoleName" :close-on-click-modal="false" width="60%"
      top="3vh">
      <!-- <div>
        <el-input v-model="userViewModel.UserName" size="small" placeholder="姓名" style="width: 200px;"
          class="filter-item" @keyup.enter.native="queryUser" />
        <el-input v-model="userViewModel.LoginName" size="small" placeholder="登录名" style="width: 200px;"
          class="filter-item" @keyup.enter.native="queryUser" />
        <el-input v-model="userViewModel.MobilePhone" size="small" placeholder="手机号" style="width: 200px;"
          class="filter-item" @keyup.enter.native="queryUser" />
        <el-button type="primary" @click="queryUser" size="small" icon="el-icon-search">查询</el-button>
        <el-button type="primary" @click="refreshUser" size="small" icon="el-icon-refresh">刷新</el-button>
      </div> -->
      <el-table v-loading="loading" :header-cell-style="{background:'#eef1f6',color:'#606266'}" :data="roleUserList"
        style="width: 100%;margin-top:30px;" border @sort-change="sortChange">
        <el-table-column label="姓名" sortable="custom" prop="UserName">
          <template slot-scope="scope">{{ scope.row.UserName }}</template>
        </el-table-column>
        <el-table-column label="职员代码" prop="Unumber">
          <template slot-scope="scope">{{ scope.row.Unumber }}</template>
        </el-table-column>
        <el-table-column label="经销商号码" prop="AgentNumber">
          <template slot-scope="scope">{{ scope.row.AgentNumber }}</template>
        </el-table-column>
        <el-table-column label="登录名" sortable="custom" prop="LoginName">
          <template slot-scope="scope">{{ scope.row.LoginName }}</template>
        </el-table-column>
        <el-table-column label="手机号" sortable="custom" prop="MobilePhone">
          <template slot-scope="scope">{{ scope.row.MobilePhone }}</template>
        </el-table-column>
      </el-table>
      <!-- 分页组件：https://element.eleme.cn/#/zh-CN/component/pagination -->
      <div class="block" style="float:right;margin-top:15px;" v-if="viewModel.total>0">
        <el-pagination @size-change="handleRoleSizeChange" @current-change="handleRoleCurrentChange"
          :current-page="viewModel.page" :page-sizes="[10, 20, 30, 40,100]" :page-size="viewModel.pageSize"
          @prev-click="lastRolePage" @next-click="nextRolePage" background
          layout="total, sizes, prev, pager, next, jumper" :total="viewModel.total"></el-pagination>
      </div>
      <div style="text-align:right;margin-top: 60px;">
        <el-button type="danger" @click="dialogRoleUserVisible=false">关闭</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
  import path from "path";
  import { deepClone } from "@/utils";
  import {
    getRoutes,
    getRoleList,
    getRoleSubList,
    addRole,
    deleteRole,
    updateRole,
    getRoleUser,
    handleRoleUser,
    getRoleUserList,
    getRoleUserItems,
    handleBatchRoleUser
  } from "@/api/role";
  import { getUserList } from '@/api/user'
  import { getRoleMenus } from '@/api/menu'
  import { reqGetAreaCitys } from "@/api/areacity";

  const defaultRole = {
    id: "",
    RoleName: "",
    ParentID: "",
    ParentName: "",
    RoleAuthorizationType: "",
    Code: "",
    Text: "",
    routes: [],
    MenuIdList: [],
    HalfMenuIdList: [],
    FullMenuIdList: []
  };

  export default {
    data() {
      return {
        role: Object.assign({}, defaultRole),
        roleUser: Object.assign({}, defaultRole),
        routes: [],
        rolesList: [],
        roleRoutes: [],
        userList: [],
        roleUserList: [],
        userTypeList: [
          { value: '', label: '全部' },
          { value: 'USER', label: '用户' },
          { value: 'TEACHER', label: '讲师' },
          { value: 'STUDENT', label: '学生' }
        ],
        multipleSelection: [],
        dialogVisible: false,
        dialogUserVisible: false,
        dialogPerVisible: false,
        dialogRoleUserVisible: false,
        dialogType: "new",
        checkStrictly: true,
        loading: true,
        defaultProps: {
          children: "children",
          label: "title"
        },
        activeName: '0',
        userViewModel: {
          page: 1,
          pageSize: 10,
          total: 0,
          ReqestType: 0,
          RoleId: '',
          UserName: '',
          LoginName: '',
          AgentNumber:'',
          MobilePhone: '',
          Unumber: '',
          SGMWRecordJob: '',
          AreaCode: '',
          ProvinceCode: '',
          CityCode: '',
          UserType: '',
          OrderBy: 'CreateTime',//排序字段
          SortDir: '' //是否升序
        },
        query: {
          Page: 1,
          PageSize: 10000,
          Total: 0,
          OrderBy: "AreaCode",
          IsAsc: true,
          TypeLevel: -1,
          AreaCode: -1,
          AreaName: "",
          ProvinceCode: -1,
          ProvinceName: "",
          CityCode: -1,
          CityName: ""
        },
        temp: {
          ID: null,
          AreaCode: 101,
          ProvinceCode: 10001,
          CityCode: 10000001,
          DealerCode: "",
          BusinessType: "",
          DealerName: "",
          BusinessNature: "",
          ManagementCode: "",
          ManagementName: "",
          InvestCode: "",
          InvestName: ""
        },
        views: [],
        areaCitys: [],
        areaDatas: [],
        provinceDatas: [],
        cityDatas: [],
        areaTempDatas: [],
        provinceTempDatas: [],
        cityTempDatas: [],
        roleViewModel: {
          page: 1,
          pageSize: 10,
          total: 0,
          RoleName: '',
          OrderBy: 'CreateTime',
          IsAsc: ''
        },
        viewModel: {
          page: 1,
          pageSize: 10,
          total: 0,
          RoleId: '',
          OrderBy: 'CreateTime',
          IsAsc: ''
        },
        roleUserViewModel: {
          UserName: '',
          LoginName: '',
          MobilePhone: '',
          UserType: '',
          OprateType: ''  //操作类型：0.授权搜索用户，1.取消授权搜索用户
        },
        rules: {
          RoleName: [
            { required: true, message: "请输入角色名称", trigger: "blur" },
            {
              min: 1,
              max: 50,
              message: "长度在 1 到 50 个字符",
              trigger: "blur"
            }
          ],
          RoleAuthorizationType: [
            { required: true, message: "请输入角色类型", trigger: "blur" }
          ]
        },
        roleId: '',
        subRoleId: ''
      };
    },
    computed: {
      routesData() {
        return this.routes;
      }
    },
    created() {
      // Mock: get all routes and roles list from server
      this.roleId = this.$route.params && this.$route.params.id
      this.getRoutes();
      this.queryRole()
      this.searchInit()
    },
    methods: {
      // 区、省、市数据初始化
      async searchInit() {
        let res = await reqGetAreaCitys(this.query);
        if (res.code === 200) {
          this.areaCitys = res.data.Items;
          this.areaDatas = this.areaCitys.filter(s => s.TypeLevel === 1);
          this.provinceDatas = this.areaCitys.filter(s => s.TypeLevel === 2);
          this.cityDatas = this.areaCitys.filter(s => s.TypeLevel === 3);

          this.areaTempDatas = this.areaCitys.filter(s => s.TypeLevel === 1);
          if (!this.isEidt) this.temp.AreaCode = this.areaTempDatas[0].AreaCode;
        }
      },
      // 区域下拉搜索
      AreaSearch() {
        if (this.userViewModel.AreaCode) {
          this.provinceDatas = this.areaCitys.filter(
            s => s.TypeLevel === 2 && s.AreaCode === this.userViewModel.AreaCode
          );
          this.cityDatas = this.areaCitys.filter(
            s => s.TypeLevel === 3 && s.AreaCode === this.userViewModel.AreaCode
          );
        } else {
          this.provinceDatas = this.areaCitys.filter(s => s.TypeLevel === 2);
          this.cityDatas = this.areaCitys.filter(s => s.TypeLevel === 3);
        }
        this.userViewModel.ProvinceCode = null;
        this.userViewModel.CityCode = null;
        this.queryUser();
      },
      // 省份下拉搜索
      ProvinceSearch() {
        if (this.userViewModel.ProvinceCode) {
          this.cityDatas = this.areaCitys.filter(
            s =>
              s.TypeLevel === 3 && s.ProvinceCode === this.userViewModel.ProvinceCode
          );
        } else {
          if (this.userViewModel.AreaCode)
            this.cityDatas = this.areaCitys.filter(
              s => s.TypeLevel === 3 && s.AreaCode === this.userViewModel.AreaCode
            );
          else this.cityDatas = this.areaCitys.filter(s => s.TypeLevel === 3);
        }
        this.userViewModel.CityCode = null;
        this.queryUser();
      },
      // 城市下拉搜索
      CitySearch() {
        this.queryUser();
      },
      handleClick(tab, event) {
        this.userViewModel.ReqestType = this.activeName
        this.refreshUser()
      },
      async getRoleUserList() {
        this.loading = true
        var res = await getRoleUserList(this.viewModel)
        if (res) {
          this.roleUserList = res.data.UserItems
          this.viewModel.total = res.data.TotalCount
        }
        this.loading = false
      },
      viewUser(scope) {
        this.dialogRoleUserVisible = true
        this.viewModel.page = 1
        this.viewModel.RoleId = scope.row.id
        this.getRoleUserList()
        this.role = deepClone(scope.row);
      },
      lastRolePage(val) {
        this.viewModel.page = val;
      },
      nextRolePage(val) {
        this.viewModel.page = val;
      },
      handleRoleSizeChange(val) {
        this.viewModel.pageSize = val;
        this.getRoleUserList();
      },
      handleRoleCurrentChange(val) {
        this.viewModel.page = val
        this.getRoleUserList()
      },
      async getRoutes() {
        const res = await getRoutes();
        this.routes = res.data;
        console.log(this.routes)
      },
      async getRoutes() {
        const res = await getRoutes();
        this.routes = res.data;
      },
      async getRoles(roleViewModel) {
        this.loading = true;
        const res = await getRoleSubList(this.roleId);
        if (res.data) {
          this.roleViewModel.total = res.data.Total;
        }
        this.rolesList = res.data.Items;
        this.loading = false;
      },
      queryRole() {
        this.roleViewModel.page = 1;
        this.getRoles(this.roleViewModel);
      },
      refresh() {
        this.roleViewModel.RoleName = '';
        this.roleViewModel.page = 1;
        this.queryRole();
      },
      async getRoleUserItems() {
        this.loading = true
        var res = await getRoleUserItems(this.userViewModel)
        if (res.data) {
          this.userViewModel.total = res.data.TotalCount;
        }
        this.userList = res.data.Items;
        this.loading = false;
      },
      async getUserList(userViewModel) {
        this.loading = true;
        const res = await getUserList(userViewModel);
        if (res.data) {
          this.userViewModel.total = res.data.TotalCount;
        }
        this.userList = res.data.UserItems;
        this.loading = false;
        getRoleUser(this.subRoleId).then(res => {
          if (res.data && res.data.length > 0)
            this.multipleSelection = res.data
          this.toggleSelection(this.multipleSelection)
        })
      },
      queryUser() {
        this.userViewModel.page = 1;
        this.getRoleUserItems();
      },
      refreshUser() {
        this.userViewModel.UserName = '';
        this.userViewModel.LoginName = '';
        this.userViewModel.MobilePhone = '';
        this.userViewModel.UserType = '';

        this.userViewModel.AreaCode = '';
        this.userViewModel.ProvinceCode = '';
        this.userViewModel.CityCode = '';
        this.userViewModel.Unumber = '';
        this.userViewModel.AgentNumber = '';

        this.userViewModel.page = 1;
        this.getRoleUserItems();
      },
      sortChange(data) {
        const { prop, order } = data
        this.userViewModel.OrderBy = prop
        if (prop == null || prop == "")
          this.userViewModel.OrderBy = "UserID"
        if (order === 'ascending') {
          this.userViewModel.SortDir = 'asc'
        } else {
          this.userViewModel.SortDir = 'desc'
        }
        this.queryUser()
      },
      lastPage(val) {
        this.userViewModel.page = val;
      },
      nextPage(val) {
        this.userViewModel.page = val;
      },
      handleSizeChange(val) {
        this.userViewModel.pageSize = val;
        this.getRoleUserItems()
      },
      handleCurrentChange(val) {
        this.userViewModel.page = val
        this.getRoleUserItems()
      },
      addSubNode(scope) { //添加子节点
        this.role = Object.assign({}, defaultRole)
        this.role.ParentID = scope.row.id
        this.role.ParentName = scope.row.RoleName
        this.role.MenuIdList = scope.row.FullMenuIdList
        this.$nextTick(() => {
          this.$refs['role'].clearValidate() //清空上次的错误验证提示
          this.$refs.tree.setCheckedKeys(this.role.MenuIdList);
        })
        this.dialogType = 'new';
        this.dialogVisible = true;
      },
      handleViewPer(scope) {
        this.dialogPerVisible = true
        this.role = deepClone(scope.row);
        this.getRoleRoutes(scope.row.id)
      },
      async getRoleRoutes(roleId) {
        const res = await getRoleMenus(roleId);
        this.roleRoutes = res.data;
      },
      handleUser(scope) {
        this.subRoleId = scope.row.id
        this.userViewModel.RoleId = this.subRoleId
        this.activeName = '0'
        this.userViewModel.ReqestType = 0
        this.refreshUser()
        this.dialogUserVisible = true
        this.$nextTick(() => {
          this.$refs.multipleTable.clearSelection();
        });
        // getRoleUser(scope.row.id).then(res => {
        //   if (res.data && res.data.length > 0)
        //     this.multipleSelection = res.data
        //   this.toggleSelection(this.multipleSelection)
        // })
        this.role = deepClone(scope.row);
      },
      async confirmRoleUser(reqestType) {
        await handleRoleUser({ 
          RoleId: this.role.id, 
          Users: this.multipleSelection, 
          PageUserList: this.userList, 
          OprateType: reqestType })
        this.$notify({
          title: "成功",
          type: "success",
          message: "操作成功!"
        });
        this.dialogUserVisible = false
      },
      async handleBatchRoleUser(oprateType) {
        this.loading = true
        this.userViewModel.ReqestType = oprateType
        this.userViewModel.RoleId = this.subRoleId
        var res = await handleBatchRoleUser(this.userViewModel)

        this.loading = false
        if (res.code == 200) {
          this.roleUserViewModel.UserName = ''
          this.roleUserViewModel.LoginName = ''
          this.roleUserViewModel.MobilePhone = ''
          this.roleUserViewModel.UserType = ''
          this.roleUserViewModel.RoleId = ''
          this.$notify({
            title: "成功",
            type: "success",
            message: "操作成功!"
          });
          this.dialogUserVisible = false
        }
      },
      handleSelectionChange(val) {
        this.multipleSelection = val;
        // console.log(val)// list<user>
      },
      toggleSelection(rows) {
        this.$refs.multipleTable.clearSelection();
        if (rows) {
          rows.forEach(row => {
            var p = this.userList.filter(u => u.UserId == row)[0]
            this.$refs.multipleTable.toggleRowSelection(p, true);
          });
        } else {
          this.$refs.multipleTable.clearSelection();
        }
      },
      handleAddRole() {
        this.role = Object.assign({}, defaultRole);
        this.role.ParentName = "运营平台"
        if (this.$refs.tree) {
          this.$refs.tree.setCheckedKeys([]);
        }
        this.dialogType = "new";
        this.dialogVisible = true;
        this.$nextTick(() => {
          this.$refs['role'].clearValidate() //清空上次的错误验证提示
        })
      },
      handleEdit(scope) {
        this.dialogType = "edit";
        this.dialogVisible = true;
        this.role = deepClone(scope.row);
        this.$nextTick(() => {
          this.$refs['role'].clearValidate() //清空上次的错误验证提示
          this.$refs.tree.setCheckedKeys(this.role.MenuIdList);
        });
      },
      handleDelete({ $index, row }) {
        if (row.children && row.children.length > 0) {
          this.$notify({
            title: "提示",
            message: "请先删除下面的子节点!",
            type: "warning",
            duration: 3000
          });
          return false;
        }
        this.$confirm("确认删除角色?", "提示", {
          confirmButtonText: "确认",
          cancelButtonText: "取消",
          type: "warning"
        })
          .then(async () => {
            await deleteRole(row.id);
            this.$notify({
              title: "成功",
              type: "success",
              message: "操作成功!"
            });
            this.queryRole();
          })
          .catch(err => {
            console.error(err);
          });
      },
      getCheckedKeys() {
        return this.$refs.tree.getCheckedKeys();
      },
      async confirmRole(formName) {
        //如果把验证失败弹出提示代码放在validate里面则不会弹出错误提示，直接走下面的更新操作代码
        var v;
        this.$refs[formName].validate(valid => {
          v = valid;
        });
        if (!v) {
          return false;
        }
        const isEdit = this.dialogType === "edit";

        // 获取选中节点id
        const checkedKeys = this.getCheckedKeys();
        this.role.MenuIdList = checkedKeys;

        // 获取半选中节点id
        const halfkeys = this.$refs.tree.getHalfCheckedKeys();
        this.role.HalfMenuIdList = halfkeys;

        if (isEdit) {
          await updateRole(this.role);
        } else {
          await addRole(this.role)
          this.roleViewModel.page = 1
        }
        this.queryRole();
        this.dialogVisible = false;
        this.$notify({
          title: "成功",
          type: "success",
          message: "操作成功!"
        });
      }
    }
  };
</script>